require 'rubygems'
require 'bundler/setup'

require 'sinatra'
require 'erb'
require 'mysql'
require 'json'

  get '/' do
    redirect '/index.html'
  end

  get '/serverid/?' do
    erb :serverid
  end

  get '/appserver/?' do
    erb :appserver
  end
  
  get '/dbread/?' do
    @data = read_data()
    erb :dbread
  end
  
  get '/init/?' do
    write_data
  end

  private
  
  @db_name = nil
  
  def read_data()
    data = [ ]
    if @db = get_mysql
      results = query "SELECT * FROM app_test"
      puts "DEBUG: data:#{results[:data]} error:#{results[:error]}"
      data = results[:data]
      data = results[:error] if results[:error]
      puts "DEBUG: data:#{data.inspect}"
      @db.close
    end
    data
  end
  
  def write_data()
    affected_rows = 0
    if @db = get_mysql(true)
      query "CREATE DATABASE #{@db_name}", true
      query "USE #{@db_name}", true
      result = query "CREATE TABLE app_test (id CHAR(50), name CHAR(50), value CHAR(50))", true
      query "INSERT INTO app_test (id, name, value) VALUES 
                ('1','app_test1','I am in the db'),
                ('2','app_test2','I am in the db'),
                ('3','app_test3','I am in the db')
            " unless result[:error]
      affected_rows = @db.affected_rows
      @db.close
    end
    "Number of rows inserted: #{affected_rows}"
  end
  
  def query(cmd, ignore_fail=false)
    res = { :data => nil, :error => nil}
    begin
      res[:data] = @db.query(cmd)
      puts "RESULT: #{res[:data].inspect}"
    rescue Mysql::Error => e
      puts "Error code: #{e.errno} message: #{e.error}" unless ignore_fail
      res[:error] = e.error
    end
    res
  end
  
  def get_mysql(init=false)      
    options = get_service_options
    return nil unless options

    begin
      @db_name = options["name"]
      name = (init) ? nil : @db_name
      Mysql.new(options["hostname"], options["user"], options["password"],  name, options["port"])
    rescue Mysql::Error => e
      puts "Error code: #{e.errno}"
      puts "Error message: #{e.error}"
      puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")
      nil
    end
  end
  
  def get_service_options
    if services = ENV['VMC_SERVICES']
      services = JSON.parse(services)
      puts "SERVICES: #{services.inspect}"
      service = services.find {|srvc| srvc["vendor"].downcase == "mysql"}
      service["options"] if service
    else
      use_local
    end
  end
  
  def use_local
    { 
      'hostname' => 'localhost', 
      'user' => ENV["USER"], 
      'password' => nil,
      'name' => 'app_test',
      'port' => nil
    }
  end
